package com.wjc.myktapplication.page.wxaccount

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.wjc.basemodule.utils.LogTools
import com.wjc.myktapplication.data.NetworkManager
import com.wjc.myktapplication.data.bean.ArticleBean

/**
 * ClassName: com.wjc.myktapplication.page.wxaccount
 * Description:
 * JcChen on 2022.07.28.16:11
 */

//    Int类型的泛型就是页数的数据类型，一般都是整型啦，第二项看类型就知道是列表的每一项数据item。
class WxArtSource(private val authId: Int) : PagingSource<Int, ArticleBean>() {

    //    代表在refresh时,从最后请求的页面开始请求,默认返回null则是请求第一页
    override fun getRefreshKey(state: PagingState<Int, ArticleBean>): Int? {
        LogTools.d("TAG", ": getRefreshKey")
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, ArticleBean> {
        try {
            val currentPage = params.key ?: 0

            val result = NetworkManager.fetchApiService().getArticleByTag(currentPage, authId)

            // 判断了如果当前页是第一页或者最后一页，那么它的上一页或者下一页就为null
            //当前页码 小于 总页码 页面加1
            val nextPage = if (currentPage < (result.data?.pageCount ?: 0)) {
                currentPage + 1
            } else {
                //没有更多数据
                null
            }

            val prevPage = if (currentPage - 1 < 0) null else currentPage - 1

            LogTools.i("TAG", ": currentPage=$currentPage,nextPage=$nextPage,prevPage=$prevPage")

            return if (result.isSuccess() && result.data != null && result.data!!.datas != null) {
                LogTools.d("TAG", "size==:${result.data!!.datas!!.size} ，nextPage=$nextPage")
                LoadResult.Page(data = result.data!!.datas!!, prevKey = prevPage, nextKey = nextPage)
            } else LoadResult.Error(throwable = Throwable())

        } catch (e: Exception) {
            LogTools.d("TAG", ": e=$e")
            return LoadResult.Error(throwable = Throwable())
        } as Nothing

    }
}